package com.scuvc.controller.user;

import com.scuvc.controller.admin.QueryCarView;
import com.scuvc.entity.RecordInfo;
import com.scuvc.utils.ImageUtils;
import com.scuvc.utils.JMenuBarUtils;
import com.scuvc.utils.StaticUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ReturnCarView extends JFrame {

    public void returnStart(){
        setTitle("城市租车系统");
        //设置窗体起始位置
        setLocation(100,50);
        //设置窗体大小
        setSize(1170,670);
        //把图片添加到标签里
        ImageIcon img = new ImageIcon("src/images/bg_admin.jpg");
        ImageIcon bg = ImageUtils.createAlphaIcon(img,0.5f,
                img.getIconWidth(),img.getIconHeight());
        JLabel label = new JLabel(bg);
        //设置标签的大小
        label.setSize(bg.getIconWidth(),bg.getIconHeight());
        //把标签放在分层面板的最底层
        getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));
        //把窗口面板设为内容面板并设为透明，流动布局
        JPanel pan = (JPanel)getContentPane();
        pan.setOpaque(false);
        pan.setLayout(new BorderLayout());
        //设置标题栏
        setTop(pan);
        //设置左边菜单栏
        setLeft(pan);
        //设置中间表格部分
        JPanel panCenter = new JPanel();
        FlowLayout fl = new FlowLayout();
        fl.setHgap(0);
        panCenter.setLayout(fl);
        panCenter.setOpaque(false);
        //边框
        panCenter.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        panCenter.setOpaque(false);
        add(panCenter,BorderLayout.CENTER);
        //设置中间表格表头部分
        setCenterTitle(panCenter);
        //设置中间表格数据部分
        StaticUtils.refreshC = setCenterData(panCenter);

        //分页
        JPanel panDown = new JPanel();
        panDown.setLayout(new FlowLayout());
        panDown.setOpaque(false);

        JButton firstPage = new JButton("首\u3000页");
        JButton endPage = new JButton("尾\u3000页");
        JButton prePage = new JButton("上一页");
        JButton nextPage = new JButton("下一页");
        add(panDown,BorderLayout.SOUTH);

        java.util.List<JButton> jbList = new ArrayList<>();
        //存储JButton按钮的集合
        for(int i=0;i<StaticUtils.pageBean.getTotalPage();i++){
            jbList.add(new JButton(i+1+""));
        }
        panDown.add(firstPage);
        panDown.add(prePage);
        panDown.add(nextPage);
        panDown.add(endPage);
        //设置窗体大小是否可调整
        setResizable(false);
        //设置窗体是否可见
        setVisible(true);
        //单击关闭按钮执行的操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    private java.util.List<JComponent> setCenterData(JPanel panCenter) {
        List<RecordInfo> recordList = StaticUtils.recordInfoService.
                queryRecordInfoByUserIdNoReturn(StaticUtils.user.getId());
        java.util.List<JComponent> list = new ArrayList<>();
        for(int i=0;i<recordList.size();i++){
            list.add(new JLabel(recordList.get(i).getId()+""));
            list.add(new JLabel(recordList.get(i).getCarInfo().getCarNo()+""));
            list.add(new JLabel(recordList.get(i).getCarInfo().getBrand().getBrand_name()));
            list.add(new JLabel(recordList.get(i).getCarInfo().getModel().getModel_name()));
            list.add(new JLabel(recordList.get(i).getCarInfo().getCategory().getCategory_name()));
            list.add(new JLabel(recordList.get(i).getRent_date()==null?"yyyy/MM/dd":
            StaticUtils.format(recordList.get(i).getRent_date())));
            list.add(new JLabel(recordList.get(i).getReturn_date()==null?"yyyy/MM/dd":
            StaticUtils.format(recordList.get(i).getReturn_date())));
            list.add(new JLabel(recordList.get(i).getPrice()+""));
            list.add(new JLabel(recordList.get(i).getRent_amount()+""));
            if(recordList.get(i).getReturn_date()==null){
                list.add(new JButton("还\u3000车"));
            }else{
                list.add(new JLabel("已还车"));
            }
        }
        //保存数据
        StaticUtils.refreshC = list ;
        Font font = new Font("仿宋",Font.PLAIN,18);
        for(int i=0;i<list.size();i++){
            list.get(i).setFont(font);
            panCenter.add(list.get(i));
            //设置标签的边框线
            list.get(i).setBorder(BorderFactory.createLineBorder(Color.BLACK));
            //设置标签的列宽
            list.get(i).setPreferredSize(new Dimension(
                    108,40));
            if(list.get(i) instanceof JLabel){
                ((JLabel) list.get(i)).setHorizontalAlignment(SwingConstants.CENTER);
            }
            if(list.get(i) instanceof JButton){
                //给JButton按钮添加附加属性为该列的id值
                ((JButton) list.get(i)).putClientProperty("id",((JLabel)list.get(0)).getText());
                ((JButton) list.get(i)).putClientProperty("carNo",((JLabel)list.get(1)).getText());
                //给JButton按钮添加监听事件
                ((JButton) list.get(i)).addActionListener(actionListener);
            }
        }
        return list ;
    }
    //还车监听
    ActionListener actionListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton jButton = (JButton) e.getSource();
            //获取添加到button按钮的id属性值
            Object obj =  jButton.getClientProperty("id");
            Long id = Long.valueOf((String)obj);
            //获取添加到button按钮的车牌号
            obj = jButton.getClientProperty("carNo");
            String carNo = (String)obj;
            //通过id查询租赁信息获取租借时间
            RecordInfo recordInfo = StaticUtils.recordInfoService.queryRecordInfoById(id);
            //计算天数
            Date date = new Date();
            double days = calculateTime(recordInfo.getRent_date(),date);
            Long rent_amount = (long)(recordInfo.getPrice()*days);
            int row = StaticUtils.recordInfoService.update(date,rent_amount,id,carNo);
            if(row==1){
                //还车成功后数据更新
                StaticUtils.carList= StaticUtils.carInfoService.getAllPage
                        (StaticUtils.pageBean.getCurPage(),
                                StaticUtils.pageBean.getPageSize());
                UserView uv = new UserView();
                setVisible(false);
                uv.start();
            }else{
                JOptionPane.showMessageDialog(null, "还车失败","提示",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        }
        //自驾租车24小时为1天,1-6小时为半天租金,超过6小时、不满24小时,为1天租金
        private double calculateTime(Date rent_date, Date date) {
            //获取租车时间的毫秒数
            long rentTime = rent_date.getTime();
            //获取还车时间的毫秒数
            long returnTime = date.getTime();
            //计算毫秒数之差
            long time = returnTime-rentTime;
            //计算整天部分
            long day = time/1000/60/60/24;
            //计算不足整天部分
            long surplusDay = time-day*1000*60*60*24;
            //换算成小时
            double hour = surplusDay/1000/60/60;
            double hourDay = 0 ;
            if(hour<=6){
                hourDay = 0.5;
            }else{
                hourDay = 1 ;
            }
            return day+hourDay;
        }
    };


    private void setCenterTitle(JPanel panCenter) {
        panCenter.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        panCenter.setPreferredSize(new Dimension(panCenter.getWidth(),60));
        java.util.List<String> jLabelName = new ArrayList<>();
        jLabelName.add("租赁编号");
        jLabelName.add("车\u0020牌\u0020号");
        jLabelName.add("品\u3000\u3000牌");
        jLabelName.add("模\u3000\u3000式");
        jLabelName.add("类\u3000\u3000别");
        jLabelName.add("租车时间");
        jLabelName.add("还车时间");
        jLabelName.add("每日租金");
        jLabelName.add("租金总额");
        jLabelName.add("操作状态");
        List<JLabel> list = new ArrayList<>();
        for(int i=0;i<jLabelName.size();i++){
            list.add(new JLabel(jLabelName.get(i)));
        }
        Font font = new Font("仿宋",Font.BOLD,24);
        for(int i=0;i<list.size();i++){
            list.get(i).setFont(font);
            panCenter.add(list.get(i));
            //设置标签的边框线
            list.get(i).setBorder(BorderFactory.createLineBorder(Color.BLACK));
            //设置标签的列宽
            list.get(i).setPreferredSize(new Dimension(108,60));
            list.get(i).setHorizontalAlignment(SwingConstants.CENTER);
        }
    }

    private void setLeft(JPanel pan) {
        JPanel panLeft = new JPanel();
        panLeft.setLayout(new GridLayout(0,1));
        panLeft.setOpaque(false);
        //将左边面板添加到面板的左边
        pan.add(panLeft,BorderLayout.WEST);
        java.util.List<String> jMenuName = new ArrayList<>();
        jMenuName.add("业务办理");
        jMenuName.add("记录查询");
        jMenuName.add("个人中心");
        String[][] itemName = {
                {"租赁汽车","归还汽车"},
                {"查询记录"},
                {"个人信息","修改密码"}};
        JMenuBar jMenuBar = JMenuBarUtils.createJMenuBar
                (jMenuName,65,0, itemName);
        panLeft.add(jMenuBar);
        add(panLeft,BorderLayout.WEST);

        ActionListener carManage = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem jmi = (JMenuItem) e.getSource();
                String text = jmi.getText();
                if(text.equals("租赁汽车")){
                    RentCarView rcv = new RentCarView();
                    setVisible(false);
                    rcv.rentStart();
                }else if(text.equals("归还汽车")){
                    ReturnCarView rcv = new ReturnCarView();
                    setVisible(false);
                    rcv.returnStart();
                }else if(text.equals("查询车辆")){
                    QueryCarView qcv = new QueryCarView();
                    setVisible(false);
                    qcv.start();
                }
            }
        };
        StaticUtils.jmiList[0][0].addActionListener(carManage);
        StaticUtils.jmiList[0][1].addActionListener(carManage);
    }
    private void setTop(JPanel pan) {
        JPanel panTop = new JPanel();
        panTop.setLayout(new GridLayout(1,1));
        panTop.setOpaque(false);
        JLabel jTop = new JLabel("智能管家");
        jTop.setPreferredSize(new Dimension(
                jTop.getPreferredSize().width,100));
        jTop.setFont(new Font("仿宋",Font.BOLD,36));
        jTop.setHorizontalAlignment(SwingConstants.CENTER);
        panTop.add(jTop);
        pan.add(panTop,BorderLayout.NORTH);
    }
}

